<?php


namespace app\api\controller\v27;


use app\api\controller\v2\Auth;
use app\common\cachemodel\live\LiveGoodsActivity;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\NatalGoods;
use app\common\cachemodel\ZhunleActivity;
use app\common\cachemodel\ZlSynastryReport;
use app\common\lib\ConfigManage;
use app\common\lib\Util;
use app\common\model\Recode;
use Exception;
use think\Env;

/**
 * @version 2.7.0
 * 本命报告和视频详情
 * Class NatalReport
 * @package app\api\controller\v22
 */
class NatalReport extends Auth
{
    /**
     * 本命报告详情
     * @throws Exception
     */
    public function detail()
    {
        $gid = input('gid/d', 0);
        if (!in_array($gid, [39, 40, 41, 42, 52], true))
        {
            return show(config('code.error'), '未知的商品');
        }
        $rid = input('rid/d', 0);
        if (!$rid && !$this->user['rid'])
        {
            return show(406, '档案缺失，去添加档案');
        }
        $rid = $rid ?: $this->user['rid'];

        $liveId = input('live_id/d', 0);
        $liveRecordId = input('live_record_id/d', 0);
        (new LiveRecordingInfo())->checkRecordId($liveId, $liveRecordId);
        $isAppoint = input('is_appoint/d', 0);// 指定 去下单介绍页 1=>指定 0=>不指定

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || (int)$recode['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $uid = $this->user['id'];
        $NatalReportModel = new \app\common\cachemodel\NatalReport();

        if (!$gid)
        {
            return show(config('code.error'), '请求异常');
        }
        $goodsModel = new \app\common\cachemodel\Goods();
        $activingModel = new ZhunleActivity();
        //获取商品类型
        $goodData = (new NatalGoods())->getGoods();
        $goodData = array_column($goodData, null, 'id');
        $activingModel->goodsActiveInfo(7, $goodData);
        if ($liveId)
        {
            (new LiveGoodsActivity())->getLiveOrderTypeGoods($liveId, 7, $goodData, ['isCloseActive' => true]);
        }
        $unlockReport = $NatalReportModel->getNatalReport2($recode);

        if ($unlockReport && $isAppoint === 0 && isset($unlockReport[$gid]) && (int)$unlockReport[$gid]['status'] === 2)
        {   // 解锁成功
            $result = [
                'status' => 2,
                'url' => Env::get('host.domain') . '/web/natal_report/index?gid=' . $gid . '&rid=' . $rid . '&live_id=' . $liveId,
                'gname' => $goodData[$gid]['name']
            ];
        } else
        {   // 未解锁 或 解锁中
            $orderModel = new \app\common\cachemodel\Orders();
            $status = isset($unlockReport[$gid]) ? ((int)$unlockReport[$gid]['status'] === 2 ? 2 : 1) : 0;
            $unlockingData = [];
            $activeData = [];
            $lockData = [];
            $unlockData = [];
            $gname = '';
            $textNum = 0;
            $unlockNum = 0;
            $headerBg = '';
            $contentBg = '';
            $natalReportPrice = [];
            // 获取合盘报告商品
            if (Util::getSynastryReportSwitch() && Util::CheckAppVersion('2.5.2') !== '小')
            {
                $synastryReportGoods = $goodsModel->GoodsTypeInfo(17);
                $goodData = array_merge($synastryReportGoods, $goodData);
            }
            //获取报告商品图片
            $reportImage = ConfigManage::natalReportGoodImage(1);
            foreach ($goodData as $key => $item)
            {
                $item['id'] = isset($item['id']) ? (int)$item['id'] : 0;
                $discount_price = null;
                $timeRange = null;
                $goodType = (isset($item['good_type']) && $item['good_type'] === 17) ? 17 : 7;

                $unlockNumber = $orderModel->getTotalPrepaidOrder($goodType, $item['id']);

                if ($item['id'] === $gid)
                {
                    $activeInfo = $goodsModel->resetGoodsInfoArr($this, 7, $item, [], [], ['isGoodInfo' => true]);
                    $orPrice = '';
                    $activeType = 0;
                    $nowPrice = $activeInfo['price'];
                    $activeTime = 0;
                    if ($activeInfo['active_data'])
                    {
                        $orPrice = $activeInfo['price'];
                        $nowPrice = $activeInfo['active_data']['now_price'];
                        $activeType = $activeInfo['active_data']['type'];
                        $activeTime = $activeInfo['active_data']['count_down'];
                    }
                    $natalReportPrice = [
                        'or_price' => $orPrice,
                        'active_type' => $activeType,
                        'now_price' => $nowPrice,
                        'active_time' => $activeTime,
                    ];
                    $gname = $item['name'];
                    $unlockNum = $item['base_num'] + $unlockNumber;
                    $textNum = $item['text_num'];
                    $headerBg = $item['header_bg'];
                    $contentBg = $item['content_bg'];
                } else
                {
                    if ((int)$item['status'] !== 2)
                    {
                        if ($goodType === 17)
                        {
                            // 检测 是否购买过
                            $unlockStatus = (new ZlSynastryReport())->getUserHasReportUnlockStatus($uid, $rid, 0, $item['srid']);
                            $unlock_status = $unlockStatus ? 2 : 0;
                        } else
                        {
                            if (isset($unlockReport[$item['id']]))
                            {
                                if ((int)$unlockReport[$item['id']]['status'] === 2)
                                {
                                    $unlock_status = 2;//已解锁
                                } else
                                {
                                    $unlock_status = 1;//计算中
                                }
                            } else
                            {
                                $unlock_status = 0;//未解锁
                            }
                        }
                    } else
                    {
                        $unlock_status = 3;//未开放
                    }
                    if ($goodType === 17)
                    {
                        $d = [
                            'gid' => $item['id'],
                            'status' => $unlock_status,
                            'bg_img' => $item['bg_img'] ?? '',
                            'gcolor' => $item['color'] ?? '',
                            'gname' => $item['name'] ?? '',
                            'unlock_num' => $item['base_num'] + $unlockNumber,
                            'active_time' => $timeRange ?? 0,
                            'target' => 'local',
                            'link' => $unlock_status === 0 ?
                                "synastry_report_detail?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1" :    // 下单介绍页
                                "synastry_report_list?rid1={$rid}&rid2=0&srid={$item['srid']}&need_auth=1"  // 查看合盘报告列表
                        ];
                    } else
                    {
                        $d = [
                            'gid' => $item['id'],
                            'status' => $unlock_status,
                            'bg_img' => $reportImage['large'][$item['flag']] ?? '',
                            'gcolor' => $item['color'] ?? '',
                            'gname' => $NatalReportModel->gidName[$item['flag']] ?: '',
                            'unlock_num' => $item['base_num'] + $unlockNumber,
                            'active_time' => $timeRange ?? 0,
                            'target' => 'local',
                            'link' => "report_details?rid={$rid}&gid={$item['id']}&need_auth=1"
                        ];
                    }

                    if ($d['status'] === 1)
                    {   // 解锁中
                        $unlockingData[] = $d;
                    } elseif ($d['status'] === 0)
                    {   // 未解锁
                        $lockData[] = $d;
                    } elseif ($d['status'] === 2)
                    {   // 已解锁
                        $unlockData[] = $d;
                    }
                }
            }

            $result = [
                'gname' => $gname,
                'status' => $status,
                'text_num' => (int)$textNum,
                'unlock_num' => (int)$unlockNum,
                'header_bg' => $headerBg,
                'content_bg' => $contentBg,
                'natal_report_list' => array_merge($activeData, $unlockData, $unlockingData, $lockData),
                'natal_report_price' => $natalReportPrice
            ];
        }

        return show(config('code.success'), '请求成功', $result);
    }
}
